using System.Text;
using CodeIsBug.Common.Components.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace CodeIsBug.Common.Components.Jwt;

/// <summary>
/// 注入jwt
/// </summary>
public static class JwtSetup
{
    /// <summary>
    /// jwt扩展方法
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddJwtSetup(this IServiceCollection services)
    {
        services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true, //是否验证Issuer
                    ValidIssuer = AppSettings.JwtOptions.Issuer, //发行人Issuer
                    ValidateAudience = true, //是否验证Audience
                    ValidAudience = AppSettings.JwtOptions.Audience, //订阅人Audience
                    ValidateIssuerSigningKey = true, //是否验证SecurityKey
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JwtOptions.SecretKey)), // SecurityKey
                    ValidateLifetime = true, // 是否验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(30), // 过期时间容错值，解决服务器端时间不同步问题（秒）
                    RequireExpirationTime = true // 是否要求Token必须有过期时间
                };
            });
        return services;
    }
}